<template>
  <div class="training-class-student-management">
    <!-- 1. 培训班信息区域 -->
    <div class="class-info">
      <h3>培训班信息</h3>
      <div class="info-grid">
        <div class="info-item" v-for="(item, index) in classInfo" :key="index">
          <span class="label">{{ item.label }}：</span>
          <span class="value">{{ item.value }}</span>
        </div>
      </div>
    </div>

    <!-- 2. 上下结构：学员报名库（上） + 进班学员列表（下） -->
    <div class="middle-section">
      <!-- 学员报名库（上栏 - 满宽） -->
      <el-row class="section-row">
        <el-col :span="24">
          <div class="student-pool">
            <h3>学员报名库</h3>

            <!-- 筛选区折叠/展开按钮 -->
            <el-button
              type="text"
              :icon="filterCollapsed ? 'el-icon-arrow-right' : 'el-icon-arrow-down'"
              @click="toggleFilter"
              class="filter-toggle-btn"
            >
              {{ filterCollapsed ? '展开筛选条件' : '收起筛选条件' }}
            </el-button>

            <!-- 筛选区：培训项目搜索 + 项目树（可折叠） -->
            <transition name="filter-collapse">
              <div class="pool-filter-card" v-if="!filterCollapsed">
                <h4 class="filter-title">筛选条件</h4>
                <el-input
                  v-model="projectName"
                  placeholder="搜索培训项目"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
                  class="pool-search-input"
                  @input="getProjectTree"
                />
                <el-tree
                  :data="projectOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  node-key="id"
                  default-expand-all
                  highlight-current
                  @node-click="handleNodeClick"
                  class="pool-tree"
                />
              </div>
            </transition>

            <!-- 学员搜索 + 批量进班按钮 -->
            <div class="pool-operation-bar">
              <div class="search-area">
                <el-input
                  placeholder="请输入学员姓名/身份证号/单位/电话"
                  v-model="searchQuery"
                  clearable
                >
                  <template #append>
                    <el-button icon="el-icon-search" @click="searchStudents"></el-button>
                  </template>
                </el-input>
              </div>
              <el-button type="primary" icon="el-icon-plus" @click="handleBatchEnterClass" class="operation-btn">
                批量进班
              </el-button>
            </div>

            <!-- 学员报名库表格（自适应高度） -->
            <div class="table-container">
              <el-table
                :data="paginatedStudentPool"
                border
                style="width: 100%"
                @selection-change="handlePoolSelectionChange"
                size="mini"
                class="pool-table"
              >
                <el-table-column type="selection" width="60"></el-table-column>
                <el-table-column label="NO." type="index" width="100"></el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button
                      type="text"
                      size="small"
                      @click="handleEnterClass(scope.row)"
                      class="enter-class-btn"
                    >
                      <i class="el-icon-arrow-right"></i>
                      进班
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="80"></el-table-column>
                <el-table-column prop="idCard" label="身份证号" width="200" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="trainingMajor" label="培训专业" width="150"></el-table-column>
                <el-table-column prop="gender" label="性别" width="70"></el-table-column>
                <el-table-column prop="age" label="年龄" width="80"></el-table-column>
                 <el-table-column prop="feeStatus" label="缴费标志" width="80">
                  <template #default="scope">
                    <span :class="{'status-paid': scope.row.feeStatus === '已缴费', 'status-unpaid': scope.row.feeStatus === '未缴费'}">
                      {{ scope.row.feeStatus }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="docStatus" label="资料通过标志" width="100">
                  <template #default="scope">
                    <span :class="{'status-pass': scope.row.docStatus === '资料通过', 'status-fail': scope.row.docStatus === '资料未通过'}">
                      {{ scope.row.docStatus }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="phone" label="电话" width="130" :show-overflow-tooltip="true"></el-table-column>
                <!-- <el-table-column prop="company" label="单位" width="180" :show-overflow-tooltip="true"></el-table-column> -->
                <el-table-column prop="applyDate" label="报名日期"></el-table-column>
              </el-table>
            </div>

            <!-- 学员报名库分页 -->
            <div class="pagination-container">
              <el-pagination
                @size-change="handlePoolSizeChange"
                @current-change="handlePoolPageChange"
                :current-page="studentPoolPage.currentPage"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="studentPoolPage.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="studentPoolPage.total"
                size="small"
              ></el-pagination>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 进班学员列表（下栏 - 满宽） -->
      <el-row class="section-row">
        <el-col :span="24">
          <div class="entered-students">
            <h3>进班学员列表</h3>

            <!-- 批量退班按钮 -->
            <el-button type="primary" icon="el-icon-minus" @click="handleBatchExitClass" class="operation-btn exit-btn">
              批量退班
            </el-button>

            <!-- 进班学员表格（自适应高度） -->
            <div class="table-container">
              <el-table
                :data="paginatedEnteredStudents"
                border
                style="width: 100%"
                @selection-change="handleEnteredSelectionChange"
                size="mini"
                class="entered-table"
              >
                <el-table-column type="selection" width="60"></el-table-column>
                <el-table-column label="NO." type="index" width="100"></el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button
                      type="text"
                      size="small"
                      @click="handleExitClass(scope.row)"
                    >
                      退班
                    </el-button>
                    <el-button
                      type="text"
                      size="small"
                      @click="handleManageStudent(scope.row)"
                    >
                      查看
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="100"></el-table-column>
                <el-table-column prop="idCard" label="身份证号" width="180" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="trainingMajor" label="培训专业" width="120"></el-table-column>
                <el-table-column prop="registerDate" label="报名日期" width="100"></el-table-column>
                <el-table-column prop="feeStatus" label="缴费标志" width="80">
                  <template #default="scope">
                    <span :class="{'status-paid': scope.row.feeStatus === '已缴费', 'status-unpaid': scope.row.feeStatus === '未缴费'}">
                      {{ scope.row.feeStatus }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="docStatus" label="资料通过标志" width="100">
                  <template #default="scope">
                    <span :class="{'status-pass': scope.row.docStatus === '资料通过', 'status-fail': scope.row.docStatus === '资料未通过'}">
                      {{ scope.row.docStatus }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="docLack" label="资料缺项" width="120" :show-overflow-tooltip="true"></el-table-column>
                <!-- <el-table-column prop="company" label="单位" width="120" :show-overflow-tooltip="true"></el-table-column> -->
                <el-table-column prop="phone" label="电话"  :show-overflow-tooltip="true"></el-table-column>
              </el-table>
            </div>

            <!-- 进班学员列表分页 -->
            <div class="pagination-container">
              <el-pagination
                @size-change="handleEnteredSizeChange"
                @current-change="handleEnteredPageChange"
                :current-page="enteredStudentsPage.currentPage"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="enteredStudentsPage.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="enteredStudentsPage.total"
                size="small"
              ></el-pagination>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { projectTreeSelect } from "@/api/training/projects";
export default {
  name: 'TrainingStudentManagement',
  props: {
    classInfo: { type: Array, required: true, default: () => [] },
    studentPool: { type: Array, required: true, default: () => [] },
    enteredStudents: { type: Array, required: true, default: () => [] }
  },
  data() {
    return {
      searchQuery: '',
      selectedPoolStudents: [],
      selectedEnteredStudents: [],
      projectName: '',
      projectOptions: [],
      defaultProps: { children: 'children', label: 'label' },
      queryParams: { projectId: null },
      filterCollapsed: true, // 筛选区折叠状态
      // 学员报名库分页配置
      studentPoolPage: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 进班学员列表分页配置
      enteredStudentsPage: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  computed: {
    filteredStudentPool() {
      if (!this.searchQuery.trim()) return this.studentPool;
      const query = this.searchQuery.toLowerCase();
      return this.studentPool.filter(student =>
        student.name.toLowerCase().includes(query) ||
        student.idCard.includes(query) ||
        (student.company && student.company.toLowerCase().includes(query)) ||
        (student.phone && student.phone.includes(query))
      );
    },
    // 学员报名库分页后的数据
    paginatedStudentPool() {
      this.studentPoolPage.total = this.filteredStudentPool.length;
      const start = (this.studentPoolPage.currentPage - 1) * this.studentPoolPage.pageSize;
      const end = start + this.studentPoolPage.pageSize;
      return this.filteredStudentPool.slice(start, end);
    },
    // 进班学员列表分页后的数据
    paginatedEnteredStudents() {
      this.enteredStudentsPage.total = this.enteredStudents.length;
      const start = (this.enteredStudentsPage.currentPage - 1) * this.enteredStudentsPage.pageSize;
      const end = start + this.enteredStudentsPage.pageSize;
      return this.enteredStudents.slice(start, end);
    }
  },
  watch: {
    // 根据名称筛选部门树
    projectName(val) {
      this.$refs.tree?.filter(val);
      this.getProjectTree(val);
    }
  },
  mounted() {
    this.getProjectTree('');
  },
  methods: {
    // 切换筛选区折叠/展开状态
    toggleFilter() {
      this.filterCollapsed = !this.filterCollapsed;
    },

    searchStudents() {
      this.$emit('student-search', {
        query: this.searchQuery,
        projectId: this.queryParams.projectId
      });
      // 搜索后重置分页
      this.studentPoolPage.currentPage = 1;
    },
    handlePoolSelectionChange(selection) {
      this.selectedPoolStudents = selection;
    },
    handleEnteredSelectionChange(selection) {
      this.selectedEnteredStudents = selection;
    },
    handleEnterClass(student) {
        if(student.paymentStatus !== "1"){
          this.$confirm(`${student.name}未缴费，确定让学员进班？`, '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            try {
              // 执行进班操作
              this.$emit('student-enter', student);
              this.selectedPoolStudents = [];
            } catch (error) {
              console.error('进班操作出错:', error);
              this.$message.error('进班操作失败，请重试');
            }
          }).catch((action) => {
            if (action === 'cancel' || action === 'close') {
              this.$message.info('已取消进班操作');
            }
          });
        }else{
          this.$emit('student-enter', student);
        }

    },
    handleBatchEnterClass() {
  if (this.selectedPoolStudents.length === 0) {
    this.$message.warning('请选择要进班的学员');
    return;
  }

  // 1. 收集所有未缴费学员名字
  const unpaidStudents = this.selectedPoolStudents.filter(item => item.paymentStatus !== "1");
  const unpaidNames = unpaidStudents.map(item => item.name);

  // 2. 如果没有未缴费学员，直接进班
  if (unpaidStudents.length === 0) {
    this.$emit('students-batch-enter', this.selectedPoolStudents);
    this.selectedPoolStudents = [];
    return;
  }

  // 3. 有未缴费学员，弹出确认框
  const studentNames = unpaidNames.join(", ");
  this.$confirm(`${studentNames}未缴费，确定让学员进班？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 执行进班操作
      this.$emit('students-batch-enter', this.selectedPoolStudents);
      this.selectedPoolStudents = [];
    } catch (error) {
      console.error('进班操作出错:', error);
      this.$message.error('进班操作失败，请重试');
    }
  }).catch((action) => {
    if (action === 'cancel' || action === 'close') {
      this.$message.info('已取消进班操作');
    }
  });
},
    handleExitClass(student) {
      this.$emit('student-exit', student);
    },
    handleBatchExitClass() {
      if (this.selectedEnteredStudents.length === 0) {
        this.$message.warning('请选择要退班的学员');
        return;
      }
      this.$emit('students-batch-exit', this.selectedEnteredStudents);
      this.selectedEnteredStudents = [];
    },
    handleManageStudent(student) {
      this.$emit('manage-student', student);
    },
    getProjectTree(val) {
      const params = { projectName: val };
      projectTreeSelect(params).then(res => { this.projectOptions = res.data; });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.projectId = data.id;
      this.$emit('project-changed', {
        projectId: data.id,
        searchQuery: this.searchQuery
      });
      // 筛选后重置分页
      this.studentPoolPage.currentPage = 1;
    },

    // 分页相关方法
    handlePoolPageChange(val) {
      this.studentPoolPage.currentPage = val;
    },
    handlePoolSizeChange(val) {
      this.studentPoolPage.pageSize = val;
      this.studentPoolPage.currentPage = 1;
    },
    handleEnteredPageChange(val) {
      this.enteredStudentsPage.currentPage = val;
    },
    handleEnteredSizeChange(val) {
      this.enteredStudentsPage.pageSize = val;
      this.enteredStudentsPage.currentPage = 1;
    }
  }
};
</script>

<style scoped>
/* 整体容器样式 */
.training-class-student-management {
  margin: 20px;
}

/* 1. 培训班信息区域样式 */
.class-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.class-info h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f2f3f5;
  color: #1d2129;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  color: #666;
  margin-right: 5px;
  width: 100px;
  text-align: right;
}

.info-item .value {
  flex: 1;
  color: #1d2129;
}

/* 2. 上下结构模块容器 */
.middle-section {
  margin-top: 10px;
}

.section-row {
  margin-bottom: 20px;
}

/* 3. 状态颜色标识 */
.status-paid { color: #52c41a; }
.status-unpaid { color: #f56c6c; }
.status-pass { color: #52c41a; }
.status-fail { color: #f56c6c; }

/* 4. 学员报名库样式 */
.student-pool {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.student-pool h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #f2f3f5;
  color: #1d2129;
}

/* 筛选区折叠按钮 */
.filter-toggle-btn {
  align-self: flex-start;
  padding: 4px 0;
  color: #1890ff;
  font-size: 13px;
}

.filter-toggle-btn:hover {
  color: #096dd9;
}

.pool-filter-card {
  background: #fafbfc;
  border: 1px solid #f2f3f5;
  border-radius: 6px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 筛选区折叠动画 */
.filter-collapse-enter-active,
.filter-collapse-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.filter-collapse-enter,
.filter-collapse-leave-to {
  max-height: 0;
  padding: 0 12px;
  opacity: 0;
}

.filter-title {
  font-size: 14px;
  font-weight: 500;
  color: #4e5969;
  margin: 0;
}

.pool-operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.search-area {
  flex: 1;
}

.search-area .el-input {
  width: 100%;
  border-radius: 4px;
  border-color: #f2f3f5;
}

.pool-search-input {
  margin: 0 !important;
  border-radius: 4px;
  border-color: #f2f3f5;
}

.pool-tree {
  width: 100%;
  height: 180px;
  overflow-y: auto;
  border: 1px solid #f2f3f5;
  border-radius: 4px;
  padding: 8px;
  background: #fff;
}

.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
  font-weight: 500;
}

.el-tree-node__content:hover {
  background-color: #f7f8fa;
  border-radius: 4px;
}

/* 5. 进班学员列表样式 */
.entered-students {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.entered-students h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #f2f3f5;
  color: #1d2129;
}

.exit-btn {
  align-self: flex-end;
}

/* 6. 操作按钮通用样式 */
.operation-btn {
  background-color: #1890ff;
  border-color: #1890ff;
  border-radius: 4px;
}

.operation-btn:hover {
  background-color: #096dd9;
  border-color: #096dd9;
}

/* 7. 表格容器样式 - 新增 */
.table-container {
  flex: 1;
  min-height: 500px; /* 最小高度确保表格可见 */
  overflow: auto;
}

.pool-table, .entered-table {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #f2f3f5;
}

.pool-table .el-table__row, .entered-table .el-table__row {
  height: 40px;
}

.pool-table .el-table__body tr:hover > td, .entered-table .el-table__body tr:hover > td {
  background-color: #f7f8fa;
  box-shadow: inset 0 0 0 1px #e8eaed;
}

.pool-table .el-table__body tr.current-row > td {
  background-color: #e6f7ff;
  border-color: #bae7ff;
}

.pool-table .el-table .cell, .entered-table .el-table .cell {
  padding: 8px 12px;
  font-size: 13px;
  color: #1d2129;
}

/* 8. 单个进班按钮样式 */
.enter-class-btn {
  color: #1890ff;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.enter-class-btn:hover {
  color: #096dd9;
}

/* 9. 滚动条优化 */
.table-container::-webkit-scrollbar,
.pool-tree::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.table-container::-webkit-scrollbar-thumb,
.pool-tree::-webkit-scrollbar-thumb {
  background-color: #c9cdcf;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.table-container::-webkit-scrollbar-thumb:hover,
.pool-tree::-webkit-scrollbar-thumb:hover {
  background-color: #aab0b5;
}

.table-container::-webkit-scrollbar-track,
.pool-tree::-webkit-scrollbar-track {
  background-color: #f7f8fa;
  border-radius: 3px;
}

/* 10. 分页组件样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .info-grid { grid-template-columns: repeat(3, 1fr); }
}

@media (max-width: 992px) {
  .info-grid { grid-template-columns: repeat(2, 1fr); }
  .pool-operation-bar { flex-direction: column; align-items: stretch; }
}

@media (max-width: 768px) {
  .pagination-container {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>
